package server;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author: liuchong
 * @create: 2023/2/20 19:53
 * @description:
 */
public class QuotationServer {
    int port;
    public QuotationServer(int port) { this.port = port; }

    public void server() {
        try {
            //监听指定的端口
            ServerSocket server=new ServerSocket(port);
            while (true) {
                //建立连接
                Socket socket=server.accept();
                //接收客户端消息(从socket中获取输入流，并建立缓冲区进行读取)
                InputStream inputStream=socket.getInputStream();
                System.out.println("客户端端口号："+socket.getPort());
                byte[] outPut=new byte[4096];
//                File file = new File("output/quotation_data.txt");
//                BufferedWriter bf = new BufferedWriter(new FileWriter(file));
                while (inputStream.read(outPut)>0) {
                    String result=new String(outPut);
                    System.out.println("客户端消息："+result);
//                    try {
//                        bf.write(result);
//                        bf.newLine();
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                    finally {
//                        try {
//                            bf.close();
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//                    }
                    out(result);
                }
//                try {
//                    bf.close();
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
                //给客户端发送消息
                OutputStream outputStream=socket.getOutputStream();
                outputStream.write("已收到你发来的消息!!".getBytes());
                inputStream.close();
                outputStream.close();
                socket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void out(String result) throws IOException {
        File file = new File("output/quotationOut.txt");
        BufferedWriter bf = new BufferedWriter(new FileWriter(file));
        try {
            bf.write(result);
            bf.newLine();
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            try {
                bf.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
